#  包含钉钉消息，邮件
from dingtalkchatbot.chatbot import DingtalkChatbot
from config.config import *
import zmail
import requests
import json
import time
from utils.get_test_result_data import get_test_result_data
from utils.config_parser import GetConfig


class SendMessage:
    def __init__(self):
        self.get_config = GetConfig()

        # self.report_link = report_link_new
        self.report_link = self.get_config.get_message_report_path().get("report_link")

        self.now = time.strftime("%Y-%m-%d %H:%M:%S")

        self.config_dingding = self.get_config.get_message_dingding()

        self.config_wechat = self.get_config.get_message_wechat()

        self.config_email = self.get_config.get_message_email()

        self.result = get_test_result_data()
        self.passed = self.result.get("passed", 0)
        self.failed = self.result.get("failed", 0)
        self.skipped = self.result.get("skipped", 0)

    def send_message(self):
        raise NotImplementedError("发送消息子类必须实现的方法")


class SendDingDingMessage(SendMessage):
    def send_message(self):
        webhook = self.config_dingding.get("ding_webhook")
        secret = self.config_dingding.get("ding_secret")

        # 接口测试报告
        # 1. 名字：接口自动化测试报告
        # 2. 测试时间是是什么时间
        # 3. 测试结果概述
        # 4. 测试报告链接
        ding = DingtalkChatbot(webhook, secret)

        ding.send_markdown("接口自动化测试报告", text=f"""
**接口自动化测试概述**

- **测试时间**：{self.now}
- **测试结果**：

  - 成功{self.passed}条
  - 失败{self.failed}条
  - 跳过{self.skipped}条
- **测试报告链接**：[点击访问]({self.report_link})

        """)


# 邮件发送
class SendMailMessage(SendMessage):
    def send_message(self):
        username = self.config_email.get("mail_username")
        password = self.config_email.get("mail_password")

        mail = zmail.server(username=username, password=password)
        mail.send_mail(recipients=self.config_email.get("recipients"), mail={
            "subject": "接口自动化通知",
            "content_html": "<h1>报告</h1>"
        })


class SendChatMessage(SendMessage):
    def send_message(self):
        webhook = self.config_wechat.get("chat_webhook")
        headers = self.config_wechat.get("headers")

        data = {
            "msgtype": "markdown",
            "markdown": {
                "content": f"""
                
                """
            }
        }
        requests.post(url=webhook, headers=headers, data=json.dumps(data))


def send_message():
    SendDingDingMessage().send_message()

    # message_object = [
    #     SendDingDingMessage(),
    #     SendChatMessage(),
    #     SendMailMessage(),
    # ]
    #
    # for mo in message_object:
    #     mo.send_message()
